<template>
  <div class="container">
    <div class="mine-section">
      <div class="section-header">
        <h2>我的权限</h2>
      </div>
      <div class="section-content">
        <div class="game-list">
          <div v-for="game in savedGames" :key="game.gameId" class="game-item" @click="goToBackend(game)">
            <span :class="getStatusClass(cdkInfos[game.gameId]?.status)">
              {{ getStatusText(cdkInfos[game.gameId]?.status) }}
            </span>
            <div class="game-info">
              <div class="game-header">
                <h3>{{ game.gameName }}</h3>
              </div>
              <div class="game-details">
                <p>绑定: {{ game.uid }}</p>
                <p v-if="cdkInfos[game.gameId]">
                  到期时间: {{ formatTime(cdkInfos[game.gameId].useTime) }}
                </p>
              </div>
            </div>
          </div>
        </div>
        <div v-if="savedGames.length === 0" class="empty-state">
          <p>暂无保存的账号</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'UserMine'
}
</script>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const savedGames = ref([])
const cdkInfos = ref({}) // 存储 CDK 信息

// 错误提示函数
const errorTip = (message) => {
  alert(message)
}

// 获取保存的游戏列表
const loadSavedGames = () => {
  const games = JSON.parse(localStorage.getItem('savedGames') || '[]')
  savedGames.value = games.reverse() // 添加 reverse() 方法进行倒序排列
  // 获取到保存的游戏后，立即查询 CDK 信息
  if (games.length > 0) {
    getCdkInfos(games)
  }
}

// 获取 CDK 信息
const getCdkInfos = async (games) => {
  try {
    const response = await fetch("/api/cdk/infos", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(games)
    })
    const data = await response.json()
    // 将数组转换为以 gameId 为键的对象
    cdkInfos.value = data.reduce((acc, item) => {
      acc[item.gameId] = item
      return acc
    }, {})
  } catch (error) {
    console.error('获取 CDK 信息失败:', error)
    errorTip('获取 CDK 信息失败！')
  }
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '未激活'
  const date = new Date(timeStr)
  return date.toLocaleString()
}

// 获取状态文本
const getStatusText = (status) => {
  return status || '失效'
}

// 获取状态样式
const getStatusClass = (status) => {
  switch (status) {
    case '有效':
      return 'status-valid'
    case '失效':
      return 'status-invalid'
    case '过期':
      return 'status-expired'
    default:
      return 'status-unknown'
  }
}

// 跳转到后台页面
const goToBackend = (game) => {
  router.push({
    path: '/backend',
    query: {
      gameId: game.gameId,
      gameName: game.gameName
    }
  })
}

onMounted(() => {
  loadSavedGames()
})
</script>

<style scoped>
.container {
  width: 100%;
  height: 90vh;
  background-color: #f7f7f7;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.mine-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  margin: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.section-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.section-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
}

.section-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.game-list {
  min-height: 100px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
  color: #999;
}

.game-item {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #eee;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.game-item:hover {
  background-color: #e9ecef;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.game-info {
  flex: 1;
}

.game-header {
  display: flex;
  flex-direction: column;
  margin-bottom: 8px;
}

.game-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.game-details {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}

.game-details p {
  margin: 5px 0;
}

.status-valid {
  color: #5cb85c;
  background-color: rgba(92, 184, 92, 0.1);
}

.status-invalid {
  color: #d9534f;
  background-color: rgba(217, 83, 79, 0.1);
}

.status-expired {
  color: #f0ad4e;
  background-color: rgba(240, 173, 78, 0.1);
}

.status-unknown {
  color: #777;
  background-color: rgba(119, 119, 119, 0.1);
}

.status-valid,
.status-invalid,
.status-expired,
.status-unknown {
  position: absolute;
  top: 12px;
  right: 12px;
  font-weight: bold;
  font-size: 14px;
  padding: 4px 8px;
  border-radius: 4px;
}

@media (max-width: 600px) {
  .container {
    margin: 0;
  }

  .mine-section {
    margin: 0;
    border-radius: 0;
  }

  .section-header {
    padding: 15px;
  }

  .section-header h2 {
    font-size: 20px;
  }

  .section-content {
    padding: 15px;
  }

  .game-item {
    padding: 10px;
  }

  .game-header h3 {
    font-size: 14px;
  }
  
  .status-valid,
  .status-invalid,
  .status-expired,
  .status-unknown {
    font-size: 12px;
    padding: 2px 6px;
  }
}
</style>